import React, { Component,createRef } from 'react';
import {withRouter} from 'react-router-dom'
import Model from '@/model/common'

import Captcha from '@/components/Captcha'
import { Form, Input,Button,Row, Col,message,Modal} from 'antd';
const layout = {
    labelCol: {
      span: 8,
    },
    wrapperCol: {
      span: 16,
    },
  };
  const tailLayout = {
    wrapperCol: {
      offset: 4,
      span: 20,
    },
  };
class MobileLogin extends Component {
    constructor (props){
        super(props)
        //手机号
        this.getphonenum = createRef()
        //图形验证码
        this.getcaptcha = createRef()

        this.ref_captcha = createRef()
        //短信验证码
        this.getPhoneCode = createRef()
    }
    state = {
        key:'',
        token:"",
        requestId:"",
        code:'',
        loading:false,
        isModalVisible:false,
        isclicktwice:true,
        count:60,
        istrue:true
    }
    render() {
        return (
            <div>
                 <Form
                    {...layout}
                    name="basic"
                    initialValues={{
                        remember: true,
                    }}
                    onFinish={this.onFinish}
                    onFinishFailed={this.onFinishFailed}
                    >
                    <Form.Item
                        label="手机号"
                        name="mobile"
                        rules={[
                        {
                            required: true,
                            message: '请输入你的手机号！',
                        },
                        ]}
                    >
                        <Input  ref={this.getphonenum}/>
                    </Form.Item>
                    <Form.Item label="短信验证码" >
                        <Row gutter={8}>
                        <Col span={12}>
                            <Form.Item
                            name="code"
                            noStyle
                            
                            rules={[
                                {
                                required: true,
                                message: '请输入你的短信验证码！',
                                },
                            ]}
                            >
                            <Input ref={this.getPhoneCode}/>
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                        <Button onClick={this.getCode} >{this.state.isclicktwice?'获取':this.state.count}</Button>
                        </Col>
                        </Row>
                    </Form.Item>
                    <Form.Item {...tailLayout}>
                        <Button type="primary" htmlType="submit" block loading={this.state.loading}>
                        登录
                        </Button>
                    </Form.Item>
                </Form>
                <Modal title="验证码" visible={this.state.isModalVisible} onOk={this.handleOk} onCancel={this.handleCancel} okText="确认" cancelText="取消">
                    <Form>
                    <Form.Item label="图形验证码" >
                        <Row gutter={8}>
                        <Col span={14}>
                            <Form.Item
                            name="captcha"
                            noStyle
                            
                            rules={[
                                {
                                required: true,
                                message: '请输入你得到的验证码！',
                                },
                            ]}
                            >
                            <Input ref={this.getcaptcha}/>
                            </Form.Item>
                        </Col>
                        <Col span={10}>
                        <Captcha height="31.6" setKey={this.setKey} ref={this.ref_captcha}></Captcha>
                        </Col>
                        </Row>
                    </Form.Item>
                    </Form>
                </Modal>
            </div>
        );
    }
    //弹窗函数
    showModal = (flag) => {
        this.setState(
          ()=>{
            return {
              isModalVisible:flag
            }
          }
        )
        };
        //倒计时函数
        // timedown=()=>{
        //     if(this.state.count===1)
        //     {
        //         this.setState(()=>{
        //             return {
        //                 isclicktwice:true,
        //                 count:60
        //             }
        //         })
        //     }
        //     else {
        //         this.setState((state)=>{
        //             return {
        //                 count:state.count-1
        //             }
        //         })
        //         setTimeout(this.timedown(),1000)
        //     }
        
        // }
        //弹窗确认按钮
        handleOk = () => {
            if(this.state.istrue){
                
                this.setState(()=>{
                    return {
                        istrue:false
                    }
                })
               let t1= setTimeout(()=>{
                    this.setState(()=>{
                        return {
                            istrue:true
                        }
                    },()=>{
                        clearTimeout(t1)
                    })
                },2000)
            let captcha = this.getcaptcha.current.props.value
            let values= {}
            values['key'] = this.state.key
            values['captcha'] =captcha
            //图形验证码校验
            Model.captcha_get(values).then(ret=>{
                console.log(ret);
                if(ret.errNo === 0)
                {
                    message.success(ret.message,2,()=>{
                        this.setState(()=>{
                            return {
                                token:ret.context.token,
                                expire:ret.context.expire
                            }
                        },
                        ()=>{
                            //关掉弹窗 开始倒计时
                            this.showModal(false)
                            this.setState(()=>{
                                return {
                                    istrue:true
                                }
                            })
                            let pnum = this.getphonenum.current.props.value;
                            let data = {}
                                data['token'] = this.state.token;
                                data['mobile'] =pnum
                                data['type'] = 0
                            Model.sms_get(data).then(ret=>{
                                console.log(ret);
                                if(ret.errNo ===0){

                                    //判断变成倒计时
                                    this.setState(()=>{
                                        return {
                                            isclicktwice:false
                                        }
                                    }) 
                                    //倒计时
                                    let time1=setInterval(()=>{
                                        if(this.state.count===1)
                                        {
                                            clearInterval(time1)
                                            this.setState(()=>{
                                                return {
                                                    isclicktwice:true,
                                                    count:60
                                                }
                                            })
                                        }
                                        else {
                                            this.setState((state)=>{
                                                return {
                                                    count:state.count-1
                                                }
                                            })
                                        }
                                    },1000)
                                    //发送验证码
                                    message.success(ret.message,()=>{
                                        this.setState(()=>{
                                            return {
                                                requestId:ret.requestId
                                            }
                                        })
                                    })
                                }
                                else
                                message.error(ret.errText)
                            })
                        }
                        )
                    }
                    )
                }
                else 
                {
                    message.error(ret.errText)
                    let t2= setTimeout(()=>{
                        this.setState(()=>{
                            return {
                                istrue:true
                            }
                        },()=>{
                            clearTimeout(t2)
                        })
                    },2000)
                    this.ref_captcha.current.loadCaptcha()
                }
            })
        }
    }; 
          handleCancel = () => {
            this.ref_captcha.current.loadCaptcha()
            this.setState(()=>{
                return {
                    istrue:true
                }
            })
            this.showModal(false)
          }; 
        //点击获取短信验证码 先判断手机号是否合法 然后弹窗  然后输入图形验证码 确认 先验证图形验证码字符串 正确 就将进入倒计时 再发送短信请求
        //
    getCode=()=>{
        // console.log(this.getphonenum.current.props.value);
        let pnum = this.getphonenum.current.props.value;
        if(/^1[3-9]\d{9}$/.test(pnum)){
            if(this.state.isclicktwice){
            this.showModal(true)
            }
        }
        else {
            message.error("手机号格式不正确")
        }
    }
    //登录请求
    onFinish = (values) => {
        //给values里塞入参数
        let pnum = this.getphonenum.current.props.value;
         let code =   this.getPhoneCode.current.props.value
        values['code'] = code
        values['requestId'] = this.state.requestId
        values["mobile"] = pnum
        Model.mobile_login(values).then(ret=>{
            console.log(ret);
            //成功跳转至home页面
        if(ret.errNo ===0){ 
            this.setState(()=>{
            return {
               loading:true
            }
            })
            message.success(ret.message,2,()=>{
                // localStorage.setItem('jwt',ret.context.jwt)
               this.props.history.push("/home") 
            })
            }
            else{
            message.error(ret.errText)
            }
        })
      };
    onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
      };
      //从子组件获取到key并存到state里
      setKey = (key)=>{
        this.setState(()=>{
            return {
                key
            }
        })
        }
}

export default withRouter(MobileLogin);
